(function($){
    dragging = false;
    var m = Math;
    mround = function (r) {
        return r >> 0;
    };
    vendor = (/webkit/i).test(navigator.appVersion) ? 'webkit' :
    (/firefox/i).test(navigator.userAgent) ? 'Moz' :
    'opera' in window ? 'O' : '',

    // Browser capabilities
    isAndroid = (/android/gi).test(navigator.appVersion),
    isIDevice = (/iphone|ipad/gi).test(navigator.appVersion),
    isPlaybook = (/playbook/gi).test(navigator.appVersion),
    isTouchPad = (/hp-tablet/gi).test(navigator.appVersion),

    has3d = 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix(),
    hasTouch = 'ontouchstart' in window && !isTouchPad,
    hasTransform = vendor + 'Transform' in document.documentElement.style,
    hasTransitionEnd = isIDevice || isPlaybook,

    nextFrame = (function() {
        return window.requestAnimationFrame
        || window.webkitRequestAnimationFrame
        || window.mozRequestAnimationFrame
        || window.oRequestAnimationFrame
        || window.msRequestAnimationFrame
        || function(callback) {
            return setTimeout(callback, 17);
        }
    })(),
    cancelFrame = (function () {
        return window.cancelRequestAnimationFrame
        || window.webkitCancelRequestAnimationFrame
        || window.mozCancelRequestAnimationFrame
        || window.oCancelRequestAnimationFrame
        || window.msCancelRequestAnimationFrame
        || clearTimeout
    })(),
    
    // Events
    RESIZE_EV = 'onorientationchange' in window ? 'orientationchange' : 'resize',
    START_EV = hasTouch ? 'touchstart' : 'mousedown',
    MOVE_EV = hasTouch ? 'touchmove' : 'mousemove',
    END_EV = hasTouch ? 'touchend' : 'mouseup',
    CANCEL_EV = hasTouch ? 'touchcancel' : 'mouseup',

    // Helpers
    trnOpen = 'translate' + (has3d ? '3d(' : '('),
    trnClose = has3d ? ',0)' : ')',
    

    /**
     * -----------------
     * Possible options:
     * Pass options wrapped in single JSON
     * -----------------
     *
     * @element: "slider_wrapper",
     * @snap: false,
     * @momentum: true,
     * @vScrollbar: false,
     * @hScrollbar: false,
     *
     * @bounce : true,
     *
     * @vScroll {Boolean} (default false)
     *      Determines whether the scroller is going to move horizontally (from left to right and back, that's
     *      the default behavior when vScroll is false) or vertically (from top to bottom and back - when true
     *      value is passed in this parameter).
     *
     * @keyboard : {Boolean} (default true)
     *
     * @move : {Integer} (default 355)
     *
     * @scroller {String} (default "scroller")
     *      ID of the "scroller" element (the dark moving thing in the scroll bar), Pass null if there
     *      is no scroller, only sliding screen (for example news story or registration form).
     *
     * @vertical : {Boolean} (default false)
     *      If this is true, the iscroll is automatically centered to the middle of the
     *      screen. If false, no centering is provided.
     *
     */
    IScrollPlus = function (options)
    {
        var defaults = {
            element: "slider_wrapper",
            snap: false,
            momentum: true,
            vScrollbar: false,
            hScrollbar: false,
            bounce : true,
            vScroll : false,
            keyboard : true,
            move : 355,
            scroller : "scroller",
            vertical : false,
            arrows : true,
            //Added element whether the slider should be positioned to window or other DOMElement
            parentElement : $(window)
        };

        options = $.extend(defaults, options);

        /*
         * options.onBeforeScrollStart
         * e has type MouseEvent
         * e.target.nodeType is integer, value 1 stands for Element(2:Attr,3:Text,...)
         * 
         */
        options.onBeforeScrollStart = function (e) {
            var target = e.target;
            while (target.nodeType != 1) target = target.parentNode;

            if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA' && target.tagName != 'OBJECT')
                e.preventDefault();
        };
        var iScrollPlus = new iScroll(options.element, options);

        /*
         * iScrollPlus.getMovingElement
         * returns the only child element of wrapper element
         */
        iScrollPlus.getMovingElement = function() {            
            var wrapper = (document).getElementById(options.element);
            return wrapper.childNodes[1];
        }

        var movingElement = iScrollPlus.getMovingElement();

        var movingElementWidth = $(movingElement).width();
        var movingElementHeight = $(movingElement).height();
        var windowWidth = (options.parentElement.width());
        var windowHeight = (options.parentElement.height());

        var vScroll = options.vScroll;
        var move = (options.move == null) ? windowWidth : options.move;


        var time = 200;

        var actualLeftPositionOfElement = 10;
        var actualTopPositionOfElement = 10;

        /*
         * Add iScroll functionality by using a keyboard
         */


        iScrollPlus.vertical = function (){
            if (!options.vertical) {
                console.log("Trying to call 'vertical' on the scroller without vertical option.");
                return false;
            }
            //var movingElement = this.getMovingElement();
            var pos = options.parentElement.height()/2 - $(movingElement).outerHeight()/2 - $(scroller).outerHeight();
            $(movingElement).css({
                'top': pos + 'px'
            });
            return true;
        }

        //Moving by mouse wheel
        var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x

        
        if (document.attachEvent)  //if browser == IE
            document.attachEvent("on"+mousewheelevt, function(e){
                
                
                var detail = (e.detail);
                //delta is positive when scrolling up, negative when scrolling down
                var delta = (e.wheelDelta);

                
                
                windowWidth = (options.parentElement.width());
                windowHeight = (options.parentElement.height());
                movingElementWidth = $(movingElement).width();
                movingElementHeight = $(movingElement).height();
                actualLeftPositionOfElement = $(movingElement).position().left;
                actualTopPositionOfElement = $(movingElement).position().top;

                if(vScroll){
                    //console.log("meh: " + movingElementHeight);
                    //console.log("wh: " + windowHeight);
                    //console.log("apos: " + actualTopPositionOfElement);
                    if(((detail > 0)||(delta < 0))&&((movingElementHeight - windowHeight + 15)>(Math.abs(actualTopPositionOfElement)))){
                        //console.log("Scroll down");
                        iScrollPlus.scrollTo(0,move,time,true);
                    }
                    if(((detail < 0)||(delta > 0))&&(actualTopPositionOfElement<1)){
                        //console.log("Scroll up");
                        iScrollPlus.scrollTo(0,-move,time,true);
                    }
                }else{
                    if(((detail > 0)||(delta < 0))&&((windowWidth - actualLeftPositionOfElement) < movingElementWidth + 1)){
                        //console.log("Scroll to right");
                        iScrollPlus.scrollTo(move,0,time,true);
                    }
                    if(((detail < 0)||(delta > 0))&&(actualLeftPositionOfElement<1)){
                        //console.log("Scroll to left");
                        iScrollPlus.scrollTo(-move,0,time,true);
                    }
                }
            })
        else if (document.addEventListener) //if browser == WC3 browsers
            document.addEventListener(mousewheelevt, function(e){

                var detail = (e.detail);
                var delta = (e.wheelDelta);
                
                windowWidth = (options.parentElement.width());
                windowHeight = (options.parentElement.height());
                movingElementWidth = $(movingElement).width();
                movingElementHeight = $(movingElement).height();
                actualLeftPositionOfElement = $(movingElement).position().left;
                actualTopPositionOfElement = $(movingElement).position().top;

                var browser = navigator.userAgent;
                if(browser.indexOf("Firefox") != -1){       // Firefox hack, because of DOMObject!!
                    var stringMoz = $(movingElement).css("-moz-transform");
                    actualLeftPositionOfElement = parseInt((stringMoz.split(","))[4]);
                    actualTopPositionOfElement = parseInt((stringMoz.split(","))[5]);
                }

                if(vScroll){
                    //console.log("meh: " + movingElementHeight);
                    //console.log("wh: " + windowHeight);
                    //console.log("apos: " + actualTopPositionOfElement);
                    if(((detail > 0)||(delta < 0))&&((movingElementHeight - windowHeight + 15)>(Math.abs(actualTopPositionOfElement)))){
                        //console.log("Scroll down");
                        iScrollPlus.scrollTo(0,move,time,true);
                    }
                    if(((detail < 0)||(delta > 0))&&(actualTopPositionOfElement<1)){
                        //console.log("Scroll up");
                        iScrollPlus.scrollTo(0,-move,time,true);
                    }
                }else{
                    if(((detail > 0)||(delta < 0))&&((windowWidth - actualLeftPositionOfElement) < movingElementWidth + 1)){
                        //console.log("Scroll to right");
                        iScrollPlus.scrollTo(move,0,time,true);
                    }
                    if(((detail < 0)||(delta > 0))&&(actualLeftPositionOfElement<1)){
                        //console.log("Scroll to left");
                        iScrollPlus.scrollTo(-move,0,time,true);
                    }
                }
            }, false)

        //Arrow movement
        document.addEventListener("keydown", function(e){
            windowWidth = (options.parentElement.width());
            movingElementWidth = $(movingElement).width();
            movingElementHeight = $(movingElement).height();
            var actualLeftPositionOfElement = $(movingElement).position().left;
            var actualTopPositionOfElement = $(movingElement).position().top;

            //Scroll left by arrow movement
            if((e.which==37)&&(actualLeftPositionOfElement<1)){
                //console.log("vlevo " + actualPositionOfElement);
                iScrollPlus.scrollTo(-move,0,time,true);
            }

            //Scroll up by arrow movement
            if((e.which==38)&&(actualTopPositionOfElement<1)){
                //console.log("nahoru " + actualTopPositionOfElement);
                iScrollPlus.scrollTo(0,-move,time,true);
            }

            //Scroll right by arrow movement
            if((e.which==39)&&((windowWidth - actualLeftPositionOfElement) < movingElementWidth + move)){
                //console.log("vpravo " + actualPositionOfElement);
                iScrollPlus.scrollTo(move,0,time,true);
            }

            //Scroll down by arrow movement
            if((e.which==40)&&( ( Math.abs(actualTopPositionOfElement) + ( options.parentElement.height())) < movingElementHeight + 11 )){
                //console.log("dolu " + actualTopPositionOfElement + " " +$(window).height());
                iScrollPlus.scrollTo(0,move,time,true);
            }
        }, false)

        if(vScroll == false){
            iScrollPlus.cleanSquares = function(){
                while(true){
                    
                    var scrollbarChildren = document.getElementById("square");
                    if(scrollbarChildren != null){
                        scrollbar.removeChild(scrollbarChildren);
                    }else{
                        break;
                    }
                }
                while(true){
                    var doubleSquare = document.getElementById("doubleSquare");
                    if(doubleSquare != null){
                        scrollbar.removeChild(doubleSquare);
                    }else{
                        break;
                    }
                }
            }

            iScrollPlus.resizeSquares = function (){
                iScrollPlus.cleanSquares();
                if(moveRatio>1){
                    iScrollPlus.getMenuDiv();
                }
            };

            iScrollPlus.addSquaresToScrollbar = function (menu){

                //Remove all previous squares
                iScrollPlus.cleanSquares();

                var variable = true;
                var leftBegin = 10;
                var verticalItems = [];
                var verticalWidth;
                var menuItems = [];
                var menuItemsWidth;
                var firstMenuItemLeftPos;
                var menuWidth = ($(menu).width());
                var menuChildren = [];

                if(($(menu.childNodes).length)==3){
                    menuChildren = ($(menu.childNodes[1]).children());

                }else{
                    menuChildren = menu.childNodes;
                }

                //console.log(menuChildren);

                for(var l=0;l<menuChildren.length;l++){
                    if((menuChildren[l].className) != null){
                        if((menuChildren[l].className).indexOf("vertical")!=-1){
                            verticalItems.push(menuChildren[l]);
                            verticalWidth = ($(menuChildren[l]).width());
                        }
                        if((menuChildren[l].className).indexOf("item")!=-1){
                            menuItems.push(menuChildren[l]);
                            if(variable){
                                variable=false;
                                menuItemsWidth = ($(menuChildren[l]).width());
                                firstMenuItemLeftPos = ($(menuChildren[l]).position().left);
                            }

                        }
                    }
                }
                var sw = 10; // Margin-left for squares

                if(firstMenuItemLeftPos == null){
                    //console.log("No menu items")
                    sw = scrollbarWidth;
                }else{
                    //console.log("Menu: " + menuWidth);
                    //TODO: Zjistit sirku polozek v menu, upravit menu div dle toho!
                    sw = (firstMenuItemLeftPos*(scrollbarWidth/menuWidth));
                }

                //Add double squares into scrollbar
                for(var e=0 ; e < $(verticalItems).length; e++){
                    var doubleSquare = document.createElement("div");
                    doubleSquare.id = "doubleSquare";
                    doubleSquare.style.width = ((sw/($(verticalItems).length)) - 2*(windowWidth/verticalWidth)) + "px";
                    doubleSquare.style.left = ((sw/($(verticalItems).length)*e) + leftBegin  + "px");
                    (scrollbar).appendChild(doubleSquare);

                    if((($(verticalItems)[e].childNodes).length)==5){
                        var doubleSquareBottom = document.createElement("div");
                        doubleSquareBottom.id = "doubleSquare";
                        doubleSquareBottom.style.top = "40px";
                        doubleSquareBottom.style.width = ((sw/($(verticalItems).length)) - 2*(windowWidth/verticalWidth)) + "px";
                        doubleSquareBottom.style.left = ((sw/($(verticalItems).length)*e) + leftBegin  + "px");
                        (scrollbar).appendChild(doubleSquareBottom);
                    }
                }

                if(sw>10) leftBegin=sw;

                //Add single squares into scrollbar
                for(var k=0 ; k < $(menuItems).length; k++){
                    var sw2 = scrollbarWidth - leftBegin;
                    var square = document.createElement("div");
                    square.id = "square";
                    square.style.width = ((sw2/($(menuItems).length)-2*(windowWidth/menuItemsWidth)) + "px");
                    square.style.left =  ((sw2/($(menuItems).length)*k) + leftBegin + "px");
                    (scrollbar).appendChild(square);
                }
            }

            iScrollPlus.getMenuDiv = function (){
                if(movingElement != null){
                    var divs = $(movingElement).find("div");
                    for(var q=0;q<divs.length;q++){
                        if((divs[q].className)=="menu"){
                            iScrollPlus.addSquaresToScrollbar(divs[q]);
                        }
                    }
                }
            }

            //This fcn scroll to the most left element on the page
            iScrollPlus.scrollToLeft = function (){
                iScrollPlus.stop();
                iScrollPlus.scrollToElement(movingElement, 200);
            }

            //This function allow draging on shoter list then moving element
            iScrollPlus.allowDragOnShortList = function(){
                setTimeout(function(){
                    iScrollPlus.hScroll=true;
                    iScrollPlus.maxScrollX=0;
                    iScrollPlus.scrollerW=100000;
                }, 10)
            }

            //Hide scroller
            iScrollPlus.hideScroller = function(){
                $(scroller).css({
                    opacity: "0"
                });
                iScrollPlus.allowDragOnShortList();
            }

            //Show scroller
            iScrollPlus.showScroller = function(){
                iScrollPlus.refresh();
                $(scroller).css({
                    opacity: "0.65"
                });
            }

            //Resize scroller width correctly
            iScrollPlus.resizeScroller = function(){
                movingElementWidth = $(movingElement).width();
                windowWidth = (options.parentElement.width());
                scrollbarWidth = $(scrollbar).width();
                moveRatio = movingElementWidth / (windowWidth - scrollerMarginSum);
                windowScrollbarRatio = scrollbarWidth/windowWidth;
                if(moveRatio>1){
                    iScrollPlus.showScroller();
                    $(scroller).width(scrollbarWidth / moveRatio);
                }else{
                    iScrollPlus.hideScroller();
                }
            }


            //Set scroller and override some function from original iScroll library
            if(options.scroller != null){

                var scroller = (document).getElementById(options.scroller);
                var scrollerMarginLeft = parseInt($(scroller).css("margin-left"));
                var scrollerMarginRight = parseInt($(scroller).css("margin-right"));
                var scrollerMarginSum = scrollerMarginLeft + scrollerMarginRight;
                var scrollbar = scroller.parentNode;
                var scrollbarWidth = $(scrollbar).width();
                var moveRatio = movingElementWidth / (windowWidth - scrollerMarginSum);
                var windowScrollbarRatio = scrollbarWidth/windowWidth;

                $(scroller).draggable({
                    axis : 'x',
                    distance : 30,
                    containment : "parent",
                    drag: function(event, ui){
                        var elementScrollbarRatio = movingElementWidth / (scrollbarWidth - ($(scroller).outerWidth(true)-$(scroller).width()));
                        var browser = navigator.userAgent;
                        var elementPosition = $(movingElement).position().left;
                        if(browser.indexOf("Firefox") != -1){       // Firefox hack, because of DOMObject!!
                            var stringMoz = $(movingElement).css("-moz-transform");
                            elementPosition = parseInt((stringMoz.split(","))[4]);
                        }
                        var move = (elementPosition + (ui.position.left * elementScrollbarRatio));
                        iScrollPlus.scrollTo(move, 0, 0, true);
                    }
                });

                $(scrollbar).click(function(e){
                    iScrollPlus.stop();
                    iScrollPlus.refresh();
                    var x = e.pageX;
                    var scrollerPosition;
                    var scrollerWidth = ($(scroller).width());
                    var position = $(scrollbar).position();
                    var scrollbarLeftPos = position.left;

                    if (((($(scroller).width()) / 2) + x) > ($(scrollbar).width() - scrollerMarginSum + scrollbarLeftPos)) {
                        scrollerPosition = (scrollbarWidth - (scrollerWidth/2) - scrollerMarginSum);
                    } else if((x - ((($(scroller).width()) / 2) + scrollbarLeftPos) < scrollerMarginSum)){
                        scrollerPosition = (scrollerWidth/2);
                    } else {
                        scrollerPosition = (x - scrollbarLeftPos);
                    }

                    $(scroller).animate({
                        "left" : "+=" + (scrollerPosition - $(scroller).position().left - ($(scroller).width() / 2) )
                    }, {
                        duration : 250,
                        easing : "linear",
                        step : function(){
                            var browser = navigator.userAgent;
                            var elementPosition = ($(movingElement).position().left);
                            if(browser.indexOf("Firefox") != -1){       // Firefox hack, because of DOMObject!!
                                var stringMoz = $(movingElement).css("-moz-transform");
                                elementPosition = parseInt((stringMoz.split(","))[4]);
                            }
                            var move = (elementPosition + ($(scroller).position().left * (moveRatio / windowScrollbarRatio)));
                            iScrollPlus.scrollTo(move, 0, 0, true);
                        },
                        complete : function(){
                            var browser = navigator.userAgent;
                            var elementPosition = ($(movingElement).position().left);
                            if(browser.indexOf("Firefox") != -1){       // Firefox hack, because of DOMObject!!
                                var stringMoz = $(movingElement).css("-moz-transform");
                                elementPosition = parseInt((stringMoz.split(","))[4]);
                            }
                            var move = (elementPosition + ($(scroller).position().left * (moveRatio / windowScrollbarRatio)));
                            iScrollPlus.scrollTo(move, 0, 0, true);
                        }
                    });
                });

                iScroll.prototype._move = function (e) {
                    var that = this,
                    point = hasTouch ? e.touches[0] : e,
                    deltaX = (point.pageX - that.pointX),
                    deltaY = (point.pageY - that.pointY),
                    newX = (that.x + deltaX),
                    newY = (that.y + deltaY),
                    timestamp = e.timeStamp || Date.now();

                    if (that.options.onBeforeScrollMove) that.options.onBeforeScrollMove.call(that, e);
                    if (Math.abs(deltaX) > 3) {
                        dragging = true;
                    }
                    if (newX > 0) {
                        //console.log("1 " + newX);
                        $(scroller).css({
                            "left": "0px"
                        });
                        var shrinkRatio = newX / moveRatio;
                        $(scroller).width((scrollbarWidth / moveRatio) - (shrinkRatio * windowScrollbarRatio));

                    } else if (newX < that.maxScrollX) {
                        //console.log("2 " + newX + " " + (newX - that.maxScrollX));
                        var shrinkRatio = Math.abs((newX - that.maxScrollX) / moveRatio);
                        $(scroller).width((scrollbarWidth / moveRatio) - (shrinkRatio * windowScrollbarRatio));
                        $(scroller).css({
                            "left": -((newX / moveRatio) * windowScrollbarRatio) + "px"
                        });
                    } else {
                        //console.log("3 " + newX);
                        $(scroller).css({
                            "left": -((newX / moveRatio) * windowScrollbarRatio) + "px"
                        });
                    }

                    that.pointX = point.pageX;
                    that.pointY = point.pageY;
                    // Slow down if outside of the boundaries
                    if (newX > 0 || newX < that.maxScrollX) {
                        newX = that.options.bounce ?  that.x + (deltaX / 2) : newX >= 0 || that.maxScrollX >= 0 ? 0 : that.maxScrollX;
                    }
                    if (newY > 0 || newY < that.maxScrollY) {
                        newY = that.options.bounce ? that.y + (deltaY / 2) : newY >= 0 || that.maxScrollY >= 0 ? 0 : that.maxScrollY;
                    }

                    if (that.absDistX < 6 && that.absDistY < 6) {
                        that.distX += deltaX;
                        that.distY += deltaY;
                        that.absDistX = m.abs(that.distX);
                        that.absDistY = m.abs(that.distY);

                        return;
                    }
                    // Lock direction
                    if (that.options.lockDirection) {
                        if (that.absDistX > that.absDistY + 5) {
                            newY = that.y;
                            deltaY = 0;
                        } else if (that.absDistY > that.absDistX + 5) {
                            newX = that.x;
                            deltaX = 0;
                        }
                    }
                    that.moved = true;
                    that._pos(newX, newY);
                    that.dirX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
                    that.dirY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;

                    if(options.vertical) {
                        that.vertical();
                    }

                    if (timestamp - that.startTime > 300) {
                        that.startTime = timestamp;
                        that.startX = that.x;
                        that.startY = that.y;
                    }
                    if (that.options.onScrollMove) that.options.onScrollMove.call(that, e);
                }


                /*
                     * Override _end function from iScroll
                     * Add a timeout before your fisrt click and drag
                     */

                iScroll.prototype._end = function (e) {
                    if (hasTouch && e.touches.length != 0) return;

                    var that = this,
                    point = hasTouch ? e.changedTouches[0] : e,
                    target, ev,
                    momentumX = {
                        dist:0,
                        time:0
                    },
                    momentumY = {
                        dist:0,
                        time:0
                    },
                    duration = (e.timeStamp || Date.now()) - that.startTime,
                    newPosX = that.x,
                    newPosY = that.y,
                    newDuration;

                    that._unbind(MOVE_EV);
                    that._unbind(END_EV);
                    that._unbind(CANCEL_EV);

                    if (that.options.onBeforeScrollEnd) that.options.onBeforeScrollEnd.call(that, e);

                    // This piece of code is new
                    setTimeout(function() {
                        dragging = false;
                    }, 200);
                    // end of new code


                    if (!that.moved) {
                        if (hasTouch) {
                            // Find the last touched element
                            target = point.target;
                            while (target.nodeType != 1) target = target.parentNode;

                            if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') {
                                ev = document.createEvent('MouseEvents');
                                ev.initMouseEvent('click', true, true, e.view, 1,
                                    point.screenX, point.screenY, point.clientX, point.clientY,
                                    e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
                                    0, null);
                                ev._fake = true;
                                target.dispatchEvent(ev);
                            }
                        }

                        that._resetPos(200);
                        // this is also new
                        if(options.vertical) {
                            that.vertical();
                        }
                        // end of new
                        if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
                        return;
                    }

                    if (duration < 300 && that.options.momentum) {
                        momentumX = newPosX ? that._momentum(newPosX - that.startX, duration, -that.x, that.scrollerW - that.wrapperW + that.x, that.options.bounce ? that.wrapperW : 0) : momentumX;
                        momentumY = newPosY ? that._momentum(newPosY - that.startY, duration, -that.y, (that.maxScrollY < 0 ? that.scrollerH - that.wrapperH + that.y : 0), that.options.bounce ? that.wrapperH : 0) : momentumY;
                        newPosX = that.x + momentumX.dist;
                        newPosY = that.y + momentumY.dist;

                        if ((that.x > 0 && newPosX > 0) || (that.x < that.maxScrollX && newPosX < that.maxScrollX)) momentumX = {
                            dist:0,
                            time:0
                        };
                        if ((that.y > 0 && newPosY > 0) || (that.y < that.maxScrollY && newPosY < that.maxScrollY)) momentumY = {
                            dist:0,
                            time:0
                        };
                    }
                    if (momentumX.dist || momentumY.dist) {
                        newDuration = m.max(m.max(momentumX.time, momentumY.time), 10);

                        that.scrollTo(mround(newPosX), mround(newPosY), newDuration);
                        // vertical is new
                        if(options.vertical) {
                            that.vertical();
                        }
                        // end of new

                        if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
                        return;
                    }

                    that._resetPos(200);
                    // vertical is new
                    if(options.vertical) {
                        that.vertical();
                    }
                    // vertical is new
                    if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
                }

                /*
                     * Overide _startAni function from iScroll
                     * Add scroll functionality for scroller
                     */

                iScroll.prototype._startAni = function () {
                    var that = this,
                    startX = that.x, startY = that.y,
                    startTime = Date.now(),
                    step, easeOut,
                    animate;

                    if (that.animating) return;

                    if (!that.steps.length) {
                        that._resetPos(400);
                        return;
                    }

                    step = that.steps.shift();

                    if (step.x == startX && step.y == startY) step.time = 0;

                    that.animating = true;
                    that.moved = true;

                    if (that.options.useTransition) {
                        that._transitionTime(step.time);
                        that._pos(step.x, step.y);
                        that.animating = false;
                        if (step.time) that._bind('webkitTransitionEnd');
                        else that._resetPos(0);
                        return;
                    }

                    animate = function () {
                        var now = Date.now(),
                        newX, newY;

                        if (now >= startTime + step.time) {
                            that._pos(step.x, step.y);
                            that.animating = false;
                            if(options.vertical) {
                                that.vertical();
                            }

                            if (that.options.onAnimationEnd) that.options.onAnimationEnd.call(that);			// Execute custom code on animation end
                            that._startAni();
                            return;
                        }
                        now = (now - startTime) / step.time - 1;
                        easeOut = m.sqrt(1 - now * now);
                        newX = (step.x - startX) * easeOut + startX;
                        newY = (step.y - startY) * easeOut + startY;
                        that._pos(newX, newY);

                        if (newX > 0) {
                            $(scroller).css({
                                "left": "0px"
                            });
                            var shrinkRatio = newX / moveRatio;
                            $(scroller).width((scrollbarWidth / moveRatio) - (shrinkRatio * windowScrollbarRatio));

                        } else if (newX < that.maxScrollX) {
                            var shrinkRatio = Math.abs((newX - that.maxScrollX) / moveRatio);
                            $(scroller).width((scrollbarWidth / moveRatio) - (shrinkRatio * windowScrollbarRatio));
                            $(scroller).css({
                                "left": -(((newX) / moveRatio) * windowScrollbarRatio) + "px"
                            // "left":  Math.floor(scrollbarWidth - $(scroller).width() - (($(scroller).outerWidth(true) - $(scroller).width())))+ "px"
                            });
                        } else {
                            $(scroller).css({
                                "left": -(((newX) / moveRatio) * windowScrollbarRatio) + "px"
                            //  "left":  Math.floor(scrollbarWidth - $(scroller).width() - (($(scroller).outerWidth(true) - $(scroller).width())))+ "px"
                            });
                        }

                        if(options.vertical) {
                            that.vertical();
                        }

                        if (that.animating) that.aniTime = nextFrame(animate);
                    };
                    animate();
                }

                if (options.vertical === true) {
                    iScrollPlus.vertical();
                }
            }
        }
        
        $(document).ready( function () {
            movingElementWidth = $(movingElement).width();
            windowWidth = (options.parentElement.width());
            scrollbarWidth = $(scrollbar).width();
            moveRatio = movingElementWidth / (windowWidth - scrollerMarginSum);
            windowScrollbarRatio = scrollbarWidth/windowWidth;
            $(scroller).width(scrollbarWidth / moveRatio);
            if(vScroll==false){
                if (options.vertical) {
                    iScrollPlus.vertical();
                }
            }
            
            if ( vScroll && options.arrows ) {
                $('<div class="verticalScroller">'+
                    '<div id="up">'+
                    '<div/>'+
                    '</div>'+
                    '<div id="down">'+
                    '<div/>'+
                    '</div>'+
                    '</div>').appendTo("body");
                
                if (!$("#footer").length) {
                    $('.verticalScroller').css({
                        bottom : 10
                    });
                }
                
                
                $("#up").mousedown(function () { 
                    that = iScrollPlus;
                    timeout = setInterval(function(){
                        var actualTopPositionOfElement = $(movingElement).position().top;
                        if (actualTopPositionOfElement<1) {
                            that.scrollTo(0,-30,50,true)
                        }
                    }, 50);
                });
                
                $("#down").mousedown(function () {
                    that = iScrollPlus;
                    timeout = setInterval(function(){
                        var movingElementHeight = $(movingElement).height();
                        var actualTopPositionOfElement = $(movingElement).position().top;
                        if(( Math.abs(actualTopPositionOfElement) + ( options.parentElement.height())) < movingElementHeight + 11 ){
                            that.scrollTo(0,30,50,true);
                        }
                    }, 50);
                });
                
                $(document).mouseup(function() {
                    if (typeof timeout != "undefined" ) {
                        clearInterval(timeout);
                    }
                });
            }
        });

        $(window).load( function () {
            if(vScroll==false){
                iScrollPlus.resizeScroller();
                iScrollPlus.resizeSquares();
            }
        });

        $(window).resize( function () {
            if(vScroll==false){
                if (options.vertical) {
                    iScrollPlus.vertical();
                }
                iScrollPlus.resizeScroller();
                iScrollPlus.resizeSquares();
            }
        });
        return iScrollPlus;
    }
})(jQuery);
